package com.vf.cloud.pass.common.listener;

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.jfinal.kit.StrKit;
import com.vf.cloud.pass.common.constant.Cache;
import com.vf.cloud.pass.common.domain.biz.Config;
import com.vf.cloud.pass.common.domain.sys.Dict;
import com.vf.cloud.pass.common.domain.sys.User;
import com.vf.cloud.pass.common.util.EncryptUtil;
import com.vf.cloud.pass.common.util.UuidUtil;
import com.vf.cloud.pass.common.vo.Dispatch;
import com.vf.cloud.server.dispatch.DispatchServer;
import com.vf.cloud.server.mysql.MySQLServer;
import com.vf.cloud.server.nginx.NginxServer;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {

	@Override
	public void onApplicationEvent(ApplicationReadyEvent contextReadyEvent) {
		

		boolean isOk = MySQLServer.getInstance().run();
		if (!isOk) {
			log.error("启动基础服务mysql失败，请联系管理员.");
			return;
		}

		User user = User.dao.findbyUsername("admin");
		if (user == null) {
			user = new User();
			user.setId(UuidUtil.getUUID());
			user.setName("超级管理员");
			user.setUsername("admin");
			user.setOrgId("sys_org");
			user.setPassword(EncryptUtil.encrypt("Xxc@admin2022"));
			if (!user.save()) {
				log.error("创建默认用户失败，请联系管理员.");
				return;
			}
		}
		
		Config config=Config.dao.findById("vf_cloud_pass_2022");
		if(config==null) {
			config=new Config();
			config.setId("vf_cloud_pass_2022");
			config.setIp("127.0.0.1");
			config.setPort("8880");
			config.setDispatchPort("6666");
			config.setDispatchSecretKey(UuidUtil.genCode());
			config.save();
		}else {
			if(StrKit.isBlank(config.getDispatchSecretKey())) {
				config.setDispatchSecretKey(UuidUtil.genCode());
				config.update();
			}
		}
		
		Cache.dispatch=new Dispatch();
		Cache.dispatch.setPort(Integer.parseInt(config.getDispatchPort()));
		Cache.dispatch.setSecretKey(config.getDispatchSecretKey());
		
		DispatchServer.getInstance().run();
		
		//初始化系统必备字典
		Dict dict = Dict.dao.findByCode("Industry");
		if(dict==null) {
			dict=new Dict();
			dict.setId(UuidUtil.getUUID());
			dict.setName("行业类型");
			dict.setCode("Industry");
			dict.setStatus("0");
			dict.setOrderNum(1);
			dict.save();
		}
		/* ArtemisServer.getInstance().run(); */
		NginxServer.getInstance().run();

	}
}
